package com.community.comsys.controller;

import com.community.common.config.minio.MinioConfig;
import com.community.common.core.domain.AjaxResult;
import com.community.common.utils.minio.MinioUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import com.community.common.core.redis.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RequestMapping("/upload")
@RestController
public class UploadController {
    private static final Logger log = LoggerFactory.getLogger(UploadController.class);
    
    @Autowired
    private MinioUtils minioUtils;
    @Autowired
    private MinioConfig minioConfig;
    @Autowired
    private RedisCache redisCache;
    
    // 缓存键前缀
    private static final String CACHE_KEY_PREFIX = "comsys:upload:";
    // 缓存过期时间（分钟）
    private static final int CACHE_TIMEOUT = 30;

    /**
     * 获取MinIO基础URL（从缓存）
     */
    private String getMinioBaseUrl() {
        String cacheKey = CACHE_KEY_PREFIX + "minio:base:url";
        
        // 尝试从缓存获取
        String cachedUrl = redisCache.getCacheObject(cacheKey);
        if (cachedUrl != null) {
            log.info("✅ 从Redis缓存获取MinIO基础URL");
            return cachedUrl;
        }
        
        // 缓存未命中，从配置获取并缓存
        String baseUrl = minioConfig.getUrl() + "/" + minioConfig.getBucketName();
        redisCache.setCacheObject(cacheKey, baseUrl, CACHE_TIMEOUT, TimeUnit.MINUTES);
        log.info("MinIO基础URL已缓存到Redis");
        
        return baseUrl;
    }
    
    /**
     * 清除上传相关缓存
     */
    private void clearUploadCache() {
        log.info("清除上传相关所有缓存");
        redisCache.deleteObject(redisCache.keys(CACHE_KEY_PREFIX + "*"));
    }
    @PostMapping("/img")
    public AjaxResult uploadAvatar(@RequestParam("file") MultipartFile file){
        //1.给上传到miniIO的文件起存储的名
        String fileName = UUID.randomUUID().toString();
        //2.上传文件到minio
        String dir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String newFileName = dir + "/" + fileName;
        minioUtils.upload(file,newFileName);
        //3.获取上传后的文件url（使用缓存的基础URL）
        String url = getMinioBaseUrl() + "/" + newFileName;
        //String url = minioUtils.getFileUrl(fileName);

        return AjaxResult.success(url);
    }}
